//
//  UIUtils.m
//  WXTime
//
//  Created by wei.chen on 12-7-22.
//  Copyright (c) 2012年 www.iphonetrain.com 无限互联ios开发培训中心 All rights reserved.
//

#import "UIUtils.h"
#import <CommonCrypto/CommonDigest.h>

@implementation UIUtils

+ (NSString *)getDocumentsPath:(NSString *)fileName {
    
    //两种获取document路径的方式
//    NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documents = [paths objectAtIndex:0];
    NSString *path = [documents stringByAppendingPathComponent:fileName];
    
    return path;
}

+ (NSString*) stringFromFomate:(NSDate*) date formate:(NSString*)formate {
  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateFormat:formate];
  
  NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
  [formatter setTimeZone:timeZone];
  
  NSString *str = [formatter stringFromDate:date];
  return str;
}

+ (NSDate *) dateFromFomate:(NSString *)datestring formate:(NSString*)formate {
  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateFormat:formate];
  
  NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
  [formatter setTimeZone:timeZone];

  NSDate *date = [formatter dateFromString:datestring];
  return date;
}

//Sat Jan 12 11:50:16 +0800 2013
+ (NSString *)fomateString:(NSString *)datestring {
    NSString *formate = @"E MMM d HH:mm:ss Z yyyy";
    NSDate *createDate = [UIUtils dateFromFomate:datestring formate:formate];
    NSString *text = [UIUtils stringFromFomate:createDate formate:@"MM-dd HH:mm"];
    return text;
}

//获取时间戳
+ (NSInteger)stampFromDateString:(NSString *)dateString
{
    NSDate *date = [UIUtils dateFromFomate:dateString formate:@"yyyy-MM-dd"];
    return date.timeIntervalSince1970;
}

+ (NSString *)dateStringFromStamp:(NSInteger)stamp
{
    return [UIUtils stringFromFomate:[NSDate dateWithTimeIntervalSince1970:stamp]
                             formate:@"MM月dd日"];
}

+ (NSInteger)todayStamp
{
    return [UIUtils stampFromDateString:[UIUtils stringFromFomate:[NSDate date] formate:@"yyyy-MM-dd"]];
}

+ (UIColor *)getColor:(NSString *)hexColor {
  unsigned int red,green,blue;
  NSRange range;
  range.length = 2;
  range.location = 0;
  [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
  range.location = 2;
  [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
  range.location = 4;
  [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
  return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
}

+ (int)getRandomNumber:(int)from to:(int)to{
  int a= arc4random() % (to - from + 1);
  return (int)(from + a);
  
}

//添加底边框
+ (void)addBottomBorder:(UIView *)view color:(CGColorRef)color borderWidth:(float)borderWidth {
  CALayer *bottomBorder = [CALayer layer];
  float height=view.frame.size.height-borderWidth;
  float width=view.frame.size.width;
  bottomBorder.frame = CGRectMake(0.0f, height, width, borderWidth);
  bottomBorder.backgroundColor = color;
  [view.layer addSublayer:bottomBorder];
}


+ (void)removeShadowFromWebview:(UIWebView *)webview {
  for( UIView *view in [webview subviews] ) {
    if( [view isKindOfClass:[UIScrollView class]] ) {
      for( UIView *innerView in [view subviews] ) {
        if( [innerView isKindOfClass:[UIImageView class]] ) {
          innerView.hidden = YES;
        }
      }
    }
  }
}

+ (NSDictionary *)loadCacheData:(NSString *)pathName {
  NSString *path = [HomeDirectory stringByAppendingString:[NSString stringWithFormat:@"%@.plist",pathName]];
  NSString *plist = [[NSBundle mainBundle] pathForResource:pathName ofType:@"plist"];
  NSDictionary *data = [[NSDictionary alloc] initWithContentsOfFile:path] ? [[NSDictionary alloc] initWithContentsOfFile:plist] : [[NSDictionary alloc] initWithContentsOfFile:plist];
  return data;
}

+ (NSString *)intervalSinceNow:(NSString *) theDate {
  NSDateFormatter *date=[[NSDateFormatter alloc] init];
  [date setDateFormat:@"MM/dd/yyyy HH:mm"];
  NSDate *d=[date dateFromString:theDate];
  
  NSTimeInterval late=[d timeIntervalSince1970]*1;
  
  
  NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
  NSTimeInterval now=[dat timeIntervalSince1970]*1;
  NSString *timeString=@"";
  
  NSTimeInterval cha=now-late;
  if (cha/3600<1) {
    timeString = [NSString stringWithFormat:@"%f", cha/60];
    timeString = [timeString substringToIndex:timeString.length-7];
    if ([timeString isEqualToString:@"0"]) {
      timeString = @"刚刚更新";
    }else
    {
      timeString=[NSString stringWithFormat:@"%@分钟前", timeString];
    }
  }
  if (cha/3600>1&&cha/86400<1) {
    timeString = [NSString stringWithFormat:@"%f", cha/3600];
    timeString = [timeString substringToIndex:timeString.length-7];
    timeString=[NSString stringWithFormat:@"%@小时前", timeString];
  }
  if (cha/86400>1)
  {
    timeString = [NSString stringWithFormat:@"%f", cha/86400];
    timeString = [timeString substringToIndex:timeString.length-7];
    timeString=[NSString stringWithFormat:@"%@天前", timeString];
    
  }
  return timeString;
}

+ (NSDictionary *)DateValuesSinceNow: (NSString *) theDate{
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *d=[date dateFromString:theDate];
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    //NSLog(@"date:%@",theDate);
    //NSLog(@"d:%@",d);
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    
    NSTimeInterval cha=late-now;
    int h=(int)cha/3600;
    int m=((int)cha%3600)/60;
    int s=((int)cha%3600%60);
    
    NSString *hour=[NSString stringWithFormat:@"%d",h];
    NSString *minute=[NSString stringWithFormat:@"%d",m];
    NSString *seconds=[NSString stringWithFormat:@"%d",s];
    
    if(h<10){
        hour=[NSString stringWithFormat:@"0%d",h];
    }
    if(m<10){
        minute=[NSString stringWithFormat:@"0%d",m];
    }
    if(s<10){
        seconds=[NSString stringWithFormat:@"0%d",s];
    }
    
    NSDictionary *result=@{@"hour":hour,
                           @"minute":minute,
                           @"seconds":seconds,
                           @"total":[NSString stringWithFormat:@"%f",cha],
                           };
    return result;
}

+ (NSDictionary *)WeekValuesSinceNow: (NSString *) theDate{
    
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    //[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    
    NSDate *d=[formatter dateFromString:theDate];
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    NSDate *dat = [NSDate date];
    NSString *today=[formatter stringFromDate:dat];
    NSDate *dd=[formatter dateFromString:today];
    NSTimeInterval now=[dd timeIntervalSince1970]*1;
    
    NSTimeInterval cha=(int)now-(int)late;
    
    NSString *stage=@"0"; //1孕期 2出生 54周  3月区分 13月起
    
    if(cha>=0){
        cha++;
    }
    
    int w=ceil((float)cha/(3600*24*7));
    int m=ceil((float)cha/(3600*24*30));
    int day=fabs(ceil(cha/(3600*24)));
    
    w=w>0? w:1;
    m=m>0? m:1;
    
    if(cha<0){
        stage=@"1";
        w=ceil((280-day)/7.0);
        day=280-day;
    }else if(cha>=0 && w<=54){
        stage=@"2";
    }else{
        stage=@"3";
    }
    
    NSString *week=[NSString stringWithFormat:@"%d",w];
    NSString *month=[NSString stringWithFormat:@"%d",m];
    NSString *days=[NSString stringWithFormat:@"%d",day];
    
    NSDictionary *result=@{@"stage":stage,
                           @"week":week,
                           @"month":month,
                           @"day":days,
                           @"total":[NSString stringWithFormat:@"%f",cha],
                           };
    return result;
}



//获取当前时间戳
+ (NSInteger)getNowStamp
{
    NSDate *fromdate = [NSDate date];
    NSInteger time = [fromdate timeIntervalSince1970];
    return time;
}

//获取日期
+ (NSString *)getStringFromDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *destDateString;
    if (date == nil) {
        destDateString = [dateFormatter stringFromDate:[NSDate date]];
    }else {
        destDateString = [dateFormatter stringFromDate:date];
    }
    
    return destDateString;
}

//获取屏幕尺寸大小
+ (CGFloat)applicationSreenInch{
    CGFloat height = [UIScreen mainScreen].bounds.size.height;

    if (height == 736) {
        return 5.5;
    }else if (height == 667) {
        return 4.7;
    }else if (height == 568) {
        return 4;
    }else {
        return 3.5;
    }
}

//获取整型版本号字符串
+ (NSString *)appVersion {

    return [NSString stringWithFormat:@"%ld", (long)[Current_Build integerValue]];
}

//获取当前活动Controller
+ (UIViewController *)getCurrentViewController {
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    if ([result isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabbar = (UITabBarController *)result;
        UINavigationController *nav = tabbar.viewControllers[tabbar.selectedIndex];
        if ([nav isKindOfClass:[UINavigationController class]]) {
            UIViewController *controller = nav.viewControllers[nav.viewControllers.count - 1];
            return controller;
        }
    }
    
    return result;
}

//根据字符串解析成颜色
+ (UIColor *)getColorByString:(NSString *)colorString {
    
    NSArray *colors = [colorString componentsSeparatedByString:@","];
    if (!colors || colors.count <= 0) {
        return [UIColor clearColor];
    }
    return RGBCOLOR([colors[0] doubleValue], [colors[1] doubleValue], [colors[2] doubleValue]);
}

@end
